<% layout('/layouts/default.html', {title: '站修线倒车通知单管理', libs: ['dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header">
			<div class="box-title">
				<i class="fa icon-notebook"></i> ${text('站修线倒车通知单管理')}
			</div>
			<div class="box-tools pull-right">
				<a href="#" class="btn btn-default" id="btnSearch" title="${text('查询')}"><i class="fa fa-filter"></i> ${text('查询')}</a>
				<a href="#" class="btn btn-default" id="btnSetting" title="${text('设置')}"><i class="fa fa-navicon"></i></a>
			</div>
		</div>
		<div class="box-body">
			<#form:form id="searchForm" model="${tblXdZxxdctzd}" action="${ctx}/tbl/lineform/tblXdZxxdctzd/listData" method="post" class="form-inline"
					data-page-no="${parameter.pageNo}" data-page-size="999" data-order-by="${parameter.orderBy}">
				<div class="form-group">
					<label class="control-label">${text('日期')}：</label>
					<div class="control-inline">

						<#form:input path="addTime" readonly="true" maxlength="20" class="form-control laydate"
							dataFormat="date" data-type="date" data-format="yyyy-MM-dd" />
					</div>
				</div>
				<div class="form-group">
					<label class="control-label">${text('班别')}：</label>
					<div class="control-inline width-120">
						<#form:hidden path="remark"/>
						<#form:select path="shift" dictType="shift_type" blankOption="false" class="form-control" onchange="shiftChange()"/>
					</div>
				</div>
				<div class="form-group">
					<label class="control-label">${text('车站')}：</label>
					<div class="control-inline width-120">
						<#form:select path="dqczbh" maxlength="2" blankOption="true" items="${lineList}" itemLabel="stationName" itemValue="stationCode" class="form-control" onchange="stationChange()"/>
					</div>
				</div>
				<div class="form-group">
					<label class="control-label">${text('倒出线路')}：</label>
					<div class="control-inline width-140">
						<#form:select path="dqxlbh" maxlength="50" items="${lineListByStation}" itemLabel="" itemValue="lineCode" class="form-control" />
					</div>
				</div>
				<div class="form-group">
					<div class="control-inline">
						<#form:checkbox id="deviceNo" path="deviceNo" dictType="all_line" class="form-control" />
					</div>
				</div>
				<div class="form-group">
					<a onclick="addBtn()" class="btn btn-primary btn-sm">${text('新增')}</a>
					<button type="submit" class="btn btn-primary btn-sm">${text('查询')}</button>
					<button type="reset" class="btn btn-default btn-sm">${text('重置')}</button>
					<a onclick="delBtn()" class="btn btn-primary btn-sm">${text('删除')}</a>
					<a onclick="updBtn()" class="btn btn-primary btn-sm">${text('修改')}</a>
					<a onclick="confirmBtn()" class="btn btn-primary btn-sm">${text('确认')}</a>
					<a onclick="cancelBtn()" class="btn btn-primary btn-sm">${text('撤销')}</a>
				</div>
			</#form:form>
			<#form:form id="searchForm2" model="${tblXdZxxdctzd}" action="${ctx}/tbl/lineform/tblXdZxxdctzd/listInfo" method="post" class="form-inline"
				data-page-no="${parameter.pageNo}" data-page-size="999" data-order-by="${parameter.orderBy}">
				<#form:hidden path="recId"/>
			</#form:form>
			<div class="dataGrid2" style="display: flex">
				<div style="display: inline-block; width: 22%;margin: 10px;vertical-align: top;">
					<table id="dataGrid2" style="'width:100%;"></table>
				</div>
				<div style="display: inline-block; width: 77%;margin: 10px;vertical-align: top;">
					<table id="dataGrid" style="'width:100%"></table>
				</div>
			</div>


	<!--			<div id="dataGridPage"></div>-->
			<div id="comnfirmBox" data-url="${ctx}/tbl/lineform/tblXdZxxdctzd/form" style="display: none">
		</div>
	</div>
</div>
<% } %>
<script>
    let recId = "";
	let qrCount = null;

	$(function(){
		// 定义一个函数来更新班次和日期
		function updateShiftAndTime() {

			var $shift = $("#shift");
			var $remark = $("#remark");
			var date_now = new Date();
			var hours = date_now.getHours();
			var year = date_now.getFullYear();  // 获取年
			var month = date_now.getMonth() + 1;  // 获取月
			var day = date_now.getDate();  // 获取日
			var $addTime = $("#addTime");

			console.log(hours);
			// 设置班次和日期
			if (hours >= 19) {
				// 夜班 (19:00到0:00)，日期保持不变
				$shift.val('1').trigger('change'); // 夜班
				$remark.val('1')
				date_now.setDate(date_now.getDate() + 1);// 日期加一天
				day = date_now.getDate();  // 更新日
				month = date_now.getMonth() + 1;  // 更新月
				year = date_now.getFullYear();  // 更新年
			} else if (hours < 8) {
				// 夜班 (0:00到8:00)，日期减去一天
				$shift.val('1').trigger('change'); // 夜班
				$remark.val('1')
				date_now.setDate(date_now.getDate()); // 日期
				year = date_now.getFullYear();  // 更新年
				month = date_now.getMonth() + 1;  // 更新月
				day = date_now.getDate();  // 更新日
			} else {
				// 白班 (8:00到19:00)
				$shift.val('2').trigger('change'); // 白班
				$remark.val('2')
			}
			// 设置日期，补零处理
			$addTime.val(year + "-" + (month < 10 ? '0' + month : month) + "-" + (day < 10 ? '0' + day : day));

		}

		// 页面加载时更新一次
		updateShiftAndTime();

		// 每隔一分钟更新一次班次和日期
		// setInterval(updateShiftAndTime, 60000);
	});

	function updBtn(){
		var ids = $("#dataGrid").jqGrid("getGridParam", "selarrrow");
		var jhhString = ""; // 拼接字符串
		for(var i = 0; i < ids.length; i++){
			jhhString += "," + ids[i];
		}
		if(jhhString !== "") {
			jhhString = jhhString.substring(1);
		}

		//校验是否有确认，有不打开弹窗
		console.log($('#dataGrid').dataGrid('getRowData', ids[0]),"123546565445")
		for (var i = 0; i < ids.length; i++) {
			if($('#dataGrid').dataGrid('getRowData', ids[i]).status == "车站确认" || $('#dataGrid').dataGrid('getRowData', ids[i]).status == "列检调度确认"){
				js.showMessage('选择项有已确认的数据不允许修改。', '', 'warning', 4000);
				return;
			}
		}
		if(ids.length>0){
			$('#comnfirmBox').show();
			js.layer.open({
				type: 2,
				align:'center',
				area: ['1200px', '600px'], //宽高
				content: $('#comnfirmBox').attr('data-url')+"?recId="+ids[0]+"&ids="+jhhString,
				shade: 0.5 ,
				resize:false,//弹窗不可拖拽
				end : function(){
					$('#comnfirmBox').hide();
					$("#recId").val(recId);
					$("#searchForm2").submit();
				}
			});
		}else{
			js.showMessage('请选择一条记录。', '', 'warning', 4000);
			return;
		}
	}

	// 初始化DataGrid对象
	$('#dataGrid').dataGrid({
		searchForm: $("#searchForm2"),
		multiselect:true,
		rownumWidth:40,
		shrinkToFit:false,
		page: 1,	// 当前页码
		rowNum: 10000, // 每页显示的条数
		columnModel: [
			//{header:'${text("操作")}', name:'actions', align:"center", width:45, formatter: function(val, obj, row, act){
			//	var actions = [];
			//	if("0" == row.status) {
			//		actions.push('<a href="${ctx}/tbl/lineform/tblXdZxxdctzd/form?recId='+row.recId+'" class="btnList" title="${text("编辑站修线倒车通知单")}"><i class="fa fa-pencil"></i></a>&nbsp;');
			//
			//		return actions.join('');
			//	}else{
			//		return actions.join('');
			//	}
			//}},
			//{header:'${text("添加时间")}', name:'addTime', align:"center", index:'a.add_Time', width:120},
			{header:'${text("是否确认")}', name:'status', align:"center", index:'a.status', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel([{dictLabel:"未确认",dictValue:'0'},{dictLabel:"列检调度确认",dictValue:'1'},{dictLabel:"车站确认",dictValue:'2'}], val, '${text("")}', true);
			}},
			{header:'${text("车号")}', name:'wagonno', index:'a.wagonno', width:100, align:"center"},
			{header:'${text("设备号")}', name:'deviceNo', align:"center", index:'a.device_no', width:100},

			{header:'${text("当前车站")}', name:'dqczmc', align:"center", index:'a.dqczmc', width:100},
			{header:'${text("当前场地")}', name:'dqcdmc', align:"center", index:'a.dqcdmc', width:100},
			{header:'${text("当前线路")}', name:'dqxlmc', align:"center", index:'a.dqxlmc', width:100},
			{header:'${text("车组")}', name:'wagonGroupName', align:"center", index:'a.wagon_group_name', width:100},
			{header:'${text("是否出场")}', name:'isOutStage', align:"center", index:'a.is_out_stage', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel(${@DictUtils.getDictListJson('sfcc')}, val, '${text("")}', true);
			}},
			{header:'${text("去向")}', name:'dest', align:"center", index:'a.dest_name', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel(${@DictUtils.getDictListJson('CLQX')}, val, '${text("")}', true);
			}},
			{header:'${text("是否禁峰")}', name:'isNopeak', align:"center", index:'a.is_nopeak', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel(${@DictUtils.getDictListJson('sys_yes_no')}, val, '${text("")}', true);
			}},
			{header:'${text("出场状况")}', name:'cczk', align:"center", index:'a.cczk', width:100,formatter: function(val, obj, row, act){
					return js.getDictLabel(${@DictUtils.getDictListJson('CCZK')}, val, '${text("")}', true);
				}},
			{header:'${text("专项整治")}', name:'zxzz', align:"center", index:'a.zxzz', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel(${@DictUtils.getDictListJson('ZXZZ')}, val, '${text("")}', true);
			}},
			{header:'${text("转场地点")}', name:'zxddName', align:"center", index:'a.zxdd', width:100},
			{header:'${text("站修类型")}', name:'vehicleRepairStatus', align:"center", index:'a.vehicle_repairStatus', width:100, formatter: function(val, obj, row, act){
				return js.getDictLabel([{dictLabel:"大修",dictValue:'1'},{dictLabel:"中修",dictValue:'2'},{dictLabel:"定修",dictValue:'3'},{dictLabel:"整修",dictValue:'4'}], val, '${text("")}', true);
			}},
			{header:'${text("备注")}', name:'remark', align:"center", index:'a.remark', width:100},
			{header:'${text("列检调度")}', name:'ljddUsername', align:"center", index:'a.ljdd_username', width:100},
			{header:'${text("列检调度确认时间")}', name:'ljddConfirmTime', align:"center", index:'a.ljdd_confirm_time', width:140},
			{header:'${text("车站调度")}', name:'czddUsername', align:"center", index:'a.czdd_username', width:100},
			{header:'${text("车站调度确认时间")}', name:'czddConfirmTime', align:"center", index:'a.czdd_confirm_time', width:140},
		],
		// 数据加载前执行方法
		ajaxLoad: function(data){

		},

		onSelectRow: function(id, isSelect, event){
			const array = $('#dataGrid').dataGrid('getSelectRows')
			sessionStorage.setItem("站修线倒车通知单管理", JSON.stringify(array))
		},

		// 加载成功后执行事件
		ajaxSuccess: function(data){
			const array = JSON.parse(sessionStorage.getItem("站修线倒车通知单管理"))
			if(array && array.length > 0){
				for (const item of array) {
					$('#dataGrid').dataGrid('setSelectRow', item, false);
				}
			}
		}
	}).dataGrid('setLabel', 'rn', '序号');
	//初始化DataGrid2对象
	$('#dataGrid2').dataGrid({
		searchForm: $("#searchForm"),
		multiselect:false,
		rownumWidth:40,
		shrinkToFit:false,
		columnModel: [
			{header:'${text("新增时间")}', name:'addTime', align:"center", index:'a.add_Time', width:160},
			{header:'${text("当前线路")}', name:'dqxlmc', align:"center", index:'a.dqxlmc',width:160},
			{header:'${text("qrCOUNT")}', name:'qrCOUNT', align:"center", index:'a.qrCOUNT',width:160,hidden:true},
		],
		onSelectRow: (rowId, status, e) => {
			recId = rowId
			qrCount = $('#dataGrid2').dataGrid('getRowData', rowId).qrCOUNT;
			console.log(qrCount,'qrCount')
			$("#recId").val(recId);
			$("#searchForm2").submit();
			//移除暂存
			sessionStorage.removeItem("站修线倒车通知单管理")
			$('#dataGrid').dataGrid('resetSelection');
		},
		// 加载成功后执行事件
		ajaxSuccess: function(data){
			$('#dataGrid2').dataGrid('setSelectRow', recId, false);
			$("#recId").val(recId);
			$("#searchForm2").submit();
		}
	})

	$('button[type="reset"]').on('click', function() {
		//移除暂存
		sessionStorage.removeItem("站修线倒车通知单管理")
		$('#dataGrid').dataGrid('resetSelection');
	})
	$('button[type="submit"]').on('click', function() {
		//点击查询清空recid
		recId = "";
	})

	function shiftChange(){
		$("#remark").val($("#shift").val())
	}

	laydate.render({
		elem: '#ID-laydate-more-btns',
		btns: ['confirm']
	});

	function stationChange(){
		var params={"stationCode":$("#dqczbh").val()};//车站
		$("#dqxlbh").empty();
		$("#dqxlbh").val("");
		var url = "${ctx}/tbl/replyform/tblXdJxchsd/getLineList";

		$("input[name='deviceNo']:checkbox").each(function(){

		if((this).checked == true)
		{
		url = "${ctx}/tbl/lineform/tblXdZxxdctzd/getAllLineList";
		}
	})

		$.post(url,params,function(data){
		//debugger;
		  if(data.tblXdLjzyjlList.length!=1){
				$("#dqxlbh").append('<option value=""> </option>');
			}
		  for(var key in data.tblXdLjzyjlList){
			  var row=data.tblXdLjzyjlList[key];
			  console.log(111,key);
			  $("#dqxlbh").append('<option value="'+row.lineCode+'">'+row.line+'</option>');
		  }
	},"json");
	};

	$('#deviceNo').on('ifChecked', function(){
	var params={"stationCode":$("#dqczbh").val()};//车站
	$("#dqxlbh").empty();
	$("#dqxlbh").val("");
	var url = "${ctx}/tbl/lineform/tblXdZxxdctzd/getAllLineList";
	$.post(url,params,function(data){
		//debugger;
		  if(data.tblXdLjzyjlList.length!=1){
				$("#dqxlbh").append('<option value=""> </option>');
			}
		  for(var key in data.tblXdLjzyjlList){
			  var row=data.tblXdLjzyjlList[key];
			  console.log(111,key);
			  $("#dqxlbh").append('<option value="'+row.lineCode+'">'+row.line+'</option>');
		  }
	},"json");
	});
	$('#deviceNo').on('ifUnchecked', function(){
var params={"stationCode":$("#dqczbh").val()};//车站
$("#dqxlbh").empty();
$("#dqxlbh").val("");
var url = "${ctx}/tbl/replyform/tblXdJxchsd/getLineList";
$.post(url,params,function(data){
    console.log(222,data);
    //debugger;
      if(data.tblXdLjzyjlList.length!=1){
            $("#dqxlbh").append('<option value=""> </option>');
        }
      for(var key in data.tblXdLjzyjlList){
          var row=data.tblXdLjzyjlList[key];
          $("#dqxlbh").append('<option value="'+row.lineCode+'">'+row.line+'</option>');
      }
},"json");
});

	function delBtn(){
		if(!recId){
			js.showMessage('请选择要删除的记录。', '', 'warning', 4000);
			return;
		}
		console.log(qrCount,"qrCount");
		if(qrCount != 0){
			js.showMessage('不可删除', '', 'warning', 4000);
			return;
		}

		var msg = "确定进行【删除】操作？";
		js.confirm(msg,function(data){
			var jhhString = recId;

			$.post("${ctx}/tbl/lineform/tblXdZxxdctzd/delete",{'jhhString':jhhString},function(e){
				if(e.result == "false"){
					js.showMessage(e.message, '', 'error', 4000);
				}else{
					js.showMessage('删除成功！', '', 'success', 4000);
				}
				$("#searchForm").submit();
				recId = "";
				$("#searchForm2").submit();
			},"json")
			.error(function(data, status, xhr){
				js.showMessage('删除失败！', '', 'error', 4000);
			});
		});
	}
	function addTest() {
		js.showMessage('测试消息', '', 'error', 4000);
	}
	//新增
	function addBtn(){
		var exportLine = $("#dqxlbh").val();
		console.log(exportLine,"exportLineexportLine")
		if(exportLine == "" || !exportLine){
			js.showMessage('请选择导出线路！', '', 'warning', 4000);

			return;
		}


		// 使用 Layer 弹出确认框
		layer.open({
			type: 1, // 页面层
			title: '确认倒出', // 弹出框标题
			area: ['300px', '200px'], // 宽高
			content: '<div style="padding: 20px;">确定要倒出线路吗？</div>', // 弹出框内容
			btn: ['确定', '取消'], // 确认和取消按钮
			yes: function(index, layero){ // 点击确定后的回调函数
				// 用户点击确认后执行后台请求
				$.post("${ctx}/tbl/lineform/tblXdZxxdctzd/insertData", {'dqxlbh': exportLine}, function(e){
					console.log(e,"eeeeeeeeeeeeeeeee")
					if (e.result == "true") {
						layer.msg('数据请求成功！', {
							icon: 1,   // 1: 成功图标
							time: 3000, // 显示3秒
							shade: 0.3, // 背景透明度 (可以用来突出消息框)
							offset: 't', // 显示在页面顶部
							anim: 6     // 动画效果
						});
					} else {
						layer.msg(e.message || '数据插入失败！', {
							icon: 2,   // 2: 错误图标
							time: 3000, // 显示3秒
							shade: 0.3, // 背景透明度
							offset: 't', // 显示在页面顶部
							anim: 6     // 动画效果
						});
					}

				}, "json");

				layer.close(index); // 关闭弹出框
			},
			btn2: function(index, layero){
				// 点击取消时可以在这里写回调，默认什么都不做
				layer.close(index); // 关闭弹出框
			}
		});
	}

	//确认
	function confirmBtn(){
	var ids = $("#dataGrid").jqGrid("getGridParam", "selarrrow");
	if(ids.length==0){
		js.showMessage('请选择要确认的记录。', '', 'warning', 4000);
		return;
	}else{
		var msg = "确定进行【确认】操作？";
		js.confirm(msg,function(data){
			var jhhString = "";//拼接字符串
			for(var i=0;i<ids.length;i++){
				jhhString += ","+ids[i];
			}
			console.log(jhhString);
			if(""!=jhhString) {
				jhhString=jhhString.substring(1);
			}
			console.log(jhhString);
			$.post("${ctx}/tbl/lineform/tblXdZxxdctzd/confirm",{'ids':jhhString},function(e){
				if(e.result == "false"){
					js.showMessage(e.message, '', 'error', 4000);
				}else{
					js.showMessage('确认成功！', '', 'success', 4000);
				}

				$("#searchForm2").submit();
				},"json")
				.error(function(data, status, xhr){
					js.showMessage('确认失败！', '', 'error', 4000);
					});
		});
	}
	}

	//撤销
	function cancelBtn(){
var ids = $("#dataGrid").jqGrid("getGridParam", "selarrrow");
if(ids.length==0){
    js.showMessage('请选择要撤销的记录。', '', 'warning', 4000);
    return;
}else{
    var msg = "确定进行【撤销】操作？";
    js.confirm(msg,function(data){
        var jhhString = "";//拼接字符串
        for(var i=0;i<ids.length;i++){
            jhhString += ","+ids[i];
        }
        console.log(jhhString);
        if(""!=jhhString) {
            jhhString=jhhString.substring(1);
        }
        console.log(jhhString);
        $.post("${ctx}/tbl/lineform/tblXdZxxdctzd/cancel",{'ids':jhhString},function(e){
            if(e.result == "false"){
                js.showMessage(e.message, '', 'error', 4000);
            }else{
                js.showMessage('撤销成功！', '', 'success', 4000);
            }
			$("#searchForm2").submit();
            },"json")
            .error(function(data, status, xhr){
                js.showMessage('撤销失败！', '', 'error', 4000);
            });
    });
}
}

</script>
<style>
	.dataGrid2{
		.ui-jqgrid .ui-jqgrid-bdiv {
			height: 75vh !important;
		}
	}
	.laydate-btns-clear{
		display: none !important;
	}
</style>